/*
 * H264StreamPlayer.cpp
 *
 *  Created: 2012-05-29
 *   Author: terry
 */

#include "stdafx.h"
#include "H264StreamPlayer.h"


H264StreamPlayer::H264StreamPlayer()
{
    m_analyzer.setSink(this);
}

H264StreamPlayer::~H264StreamPlayer()
{

}

bool H264StreamPlayer::inputData(const unsigned char* buffer, size_t length)
{
    if (length == 0)
    {
        return false;
    }

    return m_analyzer.inputData(buffer, length);
}

void H264StreamPlayer::resetBuffer()
{
    m_analyzer.clear();
}

void H264StreamPlayer::flushBuffer()
{
	if (m_buffer.readable())
	{
		m_decode.inputData(m_buffer.getReadPtr(), m_buffer.readable());
		m_buffer.clear();
	}
}

void H264StreamPlayer::writePacket(NaluPacket& packet)
{
    switch (packet.type)
    {
    case NaluPacket::NALU_PPS:
    case NaluPacket::NALU_SEI:
        m_buffer.write(packet.data, packet.length);
        break;
    case NaluPacket::NALU_IFRAME:
		flushBuffer();
        m_buffer.write(packet.data, packet.length);
        m_decode.inputData(m_buffer.getReadPtr(), m_buffer.readable());
        m_buffer.clear();
        break;
    case NaluPacket::NALU_NULL:
        if (m_buffer.readable() > 0)
        {
            m_buffer.write(packet.data, packet.length);
        }
        break;
    default:
        {
			uint8_t firstByte = packet.data[packet.prefix];
			uint8_t secondByte = packet.data[packet.prefix + 1];
			if (packet.type == 0x01 && firstByte == 0x21)
			{
				uint8_t startBit = secondByte & 0x80;
				if (startBit)
				{
					if (m_buffer.readable())
					{
						m_decode.inputData(m_buffer.getReadPtr(), m_buffer.readable());
						m_buffer.clear();
					}
				}
				m_buffer.write(packet.data, packet.length);
			}
			else
			{
				if (m_buffer.readable())
				{
					m_decode.inputData(m_buffer.getReadPtr(), m_buffer.readable());
					m_buffer.clear();
				}

				m_decode.inputData(packet.data, packet.length);
			}
        }
        break;
    }
}